home *** CD-ROM | disk | FTP | other *** search
/ Developer CD Series 1994 August: Tool Chest / Dev.CD Aug 94.toast / New System Software Extensions / PlainTalk™ Speech Technologies / Text to Speech / Programming Stuff / Examples / TESample with TTS / TESample.c < prev    next >
Encoding:
C/C++ Source or Header  |  1993-09-15  |  59.1 KB  |  1,904 lines  |  [TEXT/MPS ]

  1. #define USE_SPEAKSTRING    false
  2.  
  3. /* Segmentation strategy:
  4.  
  5.    This program consists of three segments. Main contains most of the code,
  6.    including the MPW libraries, and the main program. Initialize contains
  7.    code that is only used once, during startup, and can be unloaded after the
  8.    program starts. %A5Init is automatically created by the Linker to initialize
  9.    globals for the MPW libraries and is unloaded right away. */
  10.  
  11.  
  12. /* SetPort strategy:
  13.  
  14.    Toolbox routines do not change the current port. In spite of this, in this
  15.    program we use a strategy of calling SetPort whenever we want to draw or
  16.    make calls which depend on the current port. This makes us less vulnerable
  17.    to bugs in other software which might alter the current port (such as the
  18.    bug (feature?) in many desk accessories which change the port on OpenDeskAcc).
  19.    Hopefully, this also makes the routines from this program more self-contained,
  20.    since they don't depend on the current port setting. */
  21.  
  22.  
  23. /* Clipboard strategy:
  24.  
  25.    This program does not maintain a private scrap. Whenever a cut, copy, or paste
  26.    occurs, we import/export from the public scrap to TextEdit's scrap right away,
  27.    using the TEToScrap and TEFromScrap routines. If we did use a private scrap,
  28.    the import/export would be in the activate/deactivate event and suspend/resume
  29.    event routines. */
  30.  
  31. /* A/UX is case sensitive, so use correct case for include file names */
  32. #ifndef THINK_C
  33. #include <types.h>
  34. #include <quickdraw.h>
  35. #include <fonts.h>
  36. #include <events.h>
  37. #include <controls.h>
  38. #include <windows.h>
  39. #include <menus.h>
  40. #include <textedit.h>
  41. #include <dialogs.h>
  42. #include <desk.h>
  43. #include <scrap.h>
  44. #include <toolutils.h>
  45. #include <memory.h>
  46. #include <segload.h>
  47. #include <files.h>
  48. #include <osutils.h>
  49. #include <osevents.h>
  50. #include <diskinit.h>
  51. #include <packages.h>
  52. #include <errors.h>
  53. #include <standardfile.h>
  54. #endif
  55. #include <traps.h>
  56. #include <values.h>
  57. #include "Speech.h"            /* SPEECH MANAGER */
  58. #include "TESample.h"        /* bring in all the #defines for TESample */
  59.  
  60. /* A DocumentRecord contains the WindowRecord for one of our document windows,
  61.    as well as the TEHandle for the text we are editing. Other document fields
  62.    can be added to this record as needed. For a similar example, see how the
  63.    Window Manager and Dialog Manager add fields after the GrafPort. */
  64. typedef struct {
  65.     WindowRecord    docWindow;
  66.     TEHandle        docTE;
  67.     ControlHandle    docVScroll;
  68.     ControlHandle    docHScroll;
  69.     ProcPtr            docClik;
  70. } DocumentRecord, *DocumentPeek;
  71.  
  72.  
  73.  
  74. /* The "g" prefix is used to emphasize that a variable is global. */
  75.  
  76. /* GMac is used to hold the result of a SysEnvirons call. This makes
  77.    it convenient for any routine to check the environment. It is
  78.    global information, anyway. */
  79. SysEnvRec    gMac;                /* set up by Initialize */
  80.  
  81. /* GHasWaitNextEvent is set at startup, and tells whether the WaitNextEvent
  82.    trap is available. If it is false, we know that we must call GetNextEvent. */
  83. Boolean        gHasWaitNextEvent;    /* set up by Initialize */
  84.  
  85. /* GInBackground is maintained by our OSEvent handling routines. Any part of
  86.    the program can check it to find out if it is currently in the background. */
  87. Boolean        gInBackground;        /* maintained by Initialize and DoEvent */
  88.  
  89. /* GNumDocuments is used to keep track of how many open documents there are
  90.    at any time. It is maintained by the routines that open and close documents. */
  91. short        gNumDocuments;        /* maintained by Initialize, DoNew, and DoCloseWindow */
  92.  
  93. Handle        menuBar;
  94.  
  95. /* gSpeechChan is a global speech channel which can be used for speaking */
  96. /* gSpeechStr is a global pascal string which can be used for speech */
  97. /* gSpeechErr is a global error return which can be latched if desired */
  98.  
  99. SpeechChannel    gSpeechChan = NULL;
  100. Str255            gSpeechStr = "\pT E Sample Application";
  101. unsigned char    gTextBuf [4096] = {0}; 
  102. unsigned short    gTextBufLen = 0;
  103. OSErr            gSpeechErr = noErr;
  104.  
  105. VoiceSpec        vspec[kMaxVoices];
  106. short            voiceSel;
  107.  
  108.  
  109. /* gClickMultiple, gLastClickTickCount, and gLastClickWhere are used to support triple-click to select whole line */
  110. /* gClickMultiple increments every time a mouse down event occurs within the system's GetDblTime() */
  111. long            gClickMultiple = 0;            /* 0 - idle, 1 - 1st click, 2 - double click, 3 - triple click, etc. */        
  112. long            gLastClickTickCount = 0;    /* tickcount at last mousedown */
  113. Point            gLastClickWhere = {-32768, -32768}; /* global mouse position at last mouse down */
  114.  
  115. /* Here are declarations for all of the C routines. In MPW 3.0 we can use
  116.    actual prototypes for parameter type checking. A/UX C does not grok
  117.    prototypes, so eliminate them under A/UX */
  118.  
  119. extern pascal OSErr SM_InitializeSpeechManager( void ); /* SPEECH MANAGER: INIT startup -- allocates globals, installs dispatcher */
  120.  
  121. void AlertUser( short error );
  122. void EventLoop( void );
  123. void DoEvent( EventRecord *event );
  124. void AdjustCursor( Point mouse, RgnHandle region );
  125. void GetGlobalMouse( Point *mouse );
  126. void DoGrowWindow( WindowPtr window, EventRecord *event );
  127. void DoZoomWindow( WindowPtr window, short part );
  128. void ResizeWindow( WindowPtr window );
  129. void GetLocalUpdateRgn( WindowPtr window, RgnHandle localRgn );
  130. void DoUpdate( WindowPtr window );
  131. //void DoDeactivate( WindowPtr window );
  132. void DoActivate( WindowPtr window, Boolean becomingActive );
  133. void DoContentClick( WindowPtr window, EventRecord *event );
  134. void DoKeyDown( EventRecord *event );
  135. unsigned long GetSleep( void );
  136. void CommonAction( ControlHandle control, short *amount );
  137. pascal void VActionProc( ControlHandle control, short part );
  138. pascal void HActionProc( ControlHandle control, short part );
  139. void DoIdle( void );
  140. void DrawWindow( WindowPtr window );
  141. void AdjustMenus( void );
  142. void DoMenuCommand( long menuResult );
  143. Boolean DoNew( void );
  144. void DoOpen( void );
  145. Boolean DoCloseWindow( WindowPtr window );
  146. void Terminate( void );
  147. void Initialize( void );
  148. void BigBadError( short error );
  149. void GetTERect( WindowPtr window, Rect *teRect );
  150. void AdjustViewRect( TEHandle docTE );
  151. void AdjustTE( WindowPtr window );
  152. void AdjustHV( Boolean isVert, ControlHandle control, TEHandle docTE,
  153.                 Boolean canRedraw );
  154. void AdjustScrollValues( WindowPtr window, Boolean canRedraw );
  155. void AdjustScrollSizes( WindowPtr window );
  156. void AdjustScrollbars( WindowPtr window, Boolean needsResize );
  157. pascal void PASCALCLIKLOOP(void);
  158. pascal ProcPtr GETOLDCLIKLOOP(void);
  159. Boolean IsAppWindow( WindowPtr window );
  160. Boolean IsDAWindow( WindowPtr window );
  161. Boolean TrapAvailable( short tNumber, TrapType tType );
  162.  
  163. long TrackMultipleClicks(long when, Point where);
  164. short TELineStartOffset( TEHandle te, short theLine);
  165. short TECharOffsetToLine(TEHandle te, short charOffset);
  166. void TESelectLine(TEHandle te, short theLine);
  167. OSErr SpeakTextRange(TEHandle te, short sIndex, short eIndex);
  168. void StartupSpeech( void );
  169.  
  170.  
  171. /* Define HiWrd and LoWrd macros for efficiency. */
  172. #define HiWrd(aLong)    (((aLong) >> 16) & 0xFFFF)
  173. #define LoWrd(aLong)    ((aLong) & 0xFFFF)
  174.  
  175. /* Define TopLeft and BotRight macros for convenience. Notice the implicit
  176.    dependency on the ordering of fields within a Rect */
  177. #define TopLeft(aRect)    (* (Point *) &(aRect).top)
  178. #define BotRight(aRect)    (* (Point *) &(aRect).bottom)
  179.  
  180.  
  181. /* This routine is part of the MPW runtime library. This external
  182.    reference to it is done so that we can unload its segment, %A5Init. */
  183.  
  184. extern void _DataInit( void );
  185.  
  186.  
  187. /* A reference to our assembly language routine that gets attached to the clikLoop
  188. field of our TE record. */
  189.  
  190. extern pascal void ASMCLIKLOOP();
  191.  
  192. #pragma segment Main
  193. main()
  194. {
  195.     //DebugStr("\pAt Main entry point for TESample…");
  196.  
  197.     #ifndef THINK_C
  198.         UnloadSeg((Ptr) _DataInit);        /* note that _DataInit must not be in Main! */
  199.     #endif
  200.     
  201.     /* 1.01 - call to ForceEnvirons removed */
  202.     
  203.     /*    If you have stack requirements that differ from the default,
  204.         then you could use SetApplLimit to increase StackSpace at 
  205.         this point, before calling MaxApplZone. */
  206.     MaxApplZone();                    /* expand the heap so code segments load at the top */
  207.  
  208.     Initialize();                    /* initialize the program */
  209.     
  210.     UnloadSeg((Ptr) Initialize);    /* note that Initialize must not be in Main! */
  211.  
  212.     
  213.     StartupSpeech();
  214.     
  215.  
  216.     EventLoop();                    /* call the main event loop */
  217. }
  218.  
  219.  
  220. /* Get events forever, and handle them by calling DoEvent.
  221.    Also call AdjustCursor each time through the loop. */
  222.  
  223. #pragma segment Main
  224. void EventLoop( void )
  225. {
  226.     RgnHandle    cursorRgn;
  227.     Boolean        gotEvent;
  228.     EventRecord    event;
  229.     Point        mouse;
  230.  
  231.     cursorRgn = NewRgn();            /* we’ll pass WNE an empty region the 1st time thru */
  232.     do {
  233.         /* use WNE if it is available */
  234.         if ( gHasWaitNextEvent ) {
  235.             GetGlobalMouse(&mouse);
  236.             AdjustCursor(mouse, cursorRgn);
  237.             gotEvent = WaitNextEvent(everyEvent, &event, GetSleep(), cursorRgn);
  238.         }
  239.         else {
  240.             SystemTask();
  241.             gotEvent = GetNextEvent(everyEvent, &event);
  242.         }
  243.         if ( gotEvent ) {
  244.             /* make sure we have the right cursor before handling the event */
  245.             AdjustCursor(event.where, cursorRgn);
  246.             DoEvent(&event);
  247.         } else DoIdle();
  248.         /*    If you are using modeless dialogs that have editText items,
  249.             you will want to call IsDialogEvent to give the caret a chance
  250.             to blink, even if WNE/GNE returned FALSE. However, check FrontWindow
  251.             for a non-NIL value before calling IsDialogEvent. */
  252.     } while ( true );    /* loop forever; we quit via ExitToShell */
  253. } /*EventLoop*/
  254.  
  255.  
  256. /* Do the right thing for an event. Determine what kind of event it is, and call
  257.  the appropriate routines. */
  258.  
  259. #pragma segment Main
  260. void DoEvent( EventRecord *event )
  261. {
  262.     short        part, err;
  263.     WindowPtr    window;
  264.     unsigned char key;
  265.     Point        aPoint;
  266.  
  267.     switch ( event->what ) {
  268.         case nullEvent:
  269.             /* we idle for null/mouse moved events ands for events which aren’t
  270.                 ours (see EventLoop) */
  271.             DoIdle();
  272.             break;
  273.         case mouseDown:
  274.             part = FindWindow(event->where, &window);
  275.             switch ( part ) {
  276.                 case inMenuBar:             /* process a mouse menu command (if any) */
  277.                     AdjustMenus();    /* bring ’em up-to-date */
  278.                     DoMenuCommand(MenuSelect(event->where));
  279.                     break;
  280.                 case inSysWindow:           /* let the system handle the mouseDown */
  281.                     SystemClick(event, window);
  282.                     break;
  283.                 case inContent:
  284.                     if ( window != FrontWindow() ) {
  285.                         SelectWindow(window);
  286.                         /*DoEvent(event);*/    /* use this line for "do first click" */
  287.                     } else
  288.                         DoContentClick(window, event);
  289.                     break;
  290.                 case inDrag:                /* pass screenBits.bounds to get all gDevices */
  291.                     DragWindow(window, event->where, &qd.screenBits.bounds);
  292.                     break;
  293.                 case inGoAway:
  294.                     if ( TrackGoAway(window, event->where) )
  295.                         DoCloseWindow(window); /* we don’t care if the user cancelled */
  296.                     break;
  297.                 case inGrow:
  298.                     DoGrowWindow(window, event);
  299.                     break;
  300.                 case inZoomIn:
  301.                 case inZoomOut:
  302.                 if ( TrackBox(window, event->where, part) )
  303.                         DoZoomWindow(window, part);
  304.                     break;
  305.             }
  306.             break;
  307.         case keyDown:
  308.         case autoKey:                       /* check for menukey equivalents */
  309.             key = (unsigned char) event->message & charCodeMask;
  310.             if ( event->modifiers & cmdKey ) {    /* Command key down */
  311.                 if ( event->what == keyDown ) {
  312.                     AdjustMenus();            /* enable/disable/check menu items properly */
  313.                     DoMenuCommand(MenuKey(key));
  314.                 }
  315.             } else
  316.                 DoKeyDown(event);
  317.             break;
  318.         case activateEvt:
  319.             DoActivate((WindowPtr) event->message, (event->modifiers & activeFlag) != 0);
  320.             break;
  321.         case updateEvt:
  322.             DoUpdate((WindowPtr) event->message);
  323.             break;
  324.         /*    1.01 - It is not a bad idea to at least call DIBadMount in response
  325.             to a diskEvt, so that the user can format a floppy. */
  326.         case diskEvt:
  327.             if ( HiWord(event->message) != noErr ) {
  328.                 SetPt(&aPoint, kDILeft, kDITop);
  329.                 err = DIBadMount(aPoint, event->message);
  330.             }
  331.             break;
  332.         case kOSEvent:
  333.         /*    1.02 - must BitAND with 0x0FF to get only low byte */
  334.             switch ((event->message >> 24) & 0x0FF) {        /* high byte of message */
  335.                 case kMouseMovedMessage:
  336.                     DoIdle();                    /* mouse-moved is also an idle event */
  337.                     break;
  338.                 case kSuspendResumeMessage:        /* suspend/resume is also an activate/deactivate */
  339.                     gInBackground = (event->message & kResumeMask) == 0;
  340.                     DoActivate(FrontWindow(), !gInBackground);
  341.                     break;
  342.             }
  343.             break;
  344.     }
  345. } /*DoEvent*/
  346.  
  347.  
  348. /*    Change the cursor's shape, depending on its position. This also calculates the region
  349.     where the current cursor resides (for WaitNextEvent). When the mouse moves outside of
  350.     this region, an event is generated. If there is more to the event than just
  351.     “the mouse moved”, we get called before the event is processed to make sure
  352.     the cursor is the right one. In any (ahem) event, this is called again before we
  353.     fall back into WNE. */
  354.  
  355. #pragma segment Main
  356. void AdjustCursor( Point mouse, RgnHandle region )
  357. {
  358.     WindowPtr    window;
  359.     RgnHandle    arrowRgn;
  360.     RgnHandle    iBeamRgn;
  361.     Rect        iBeamRect;
  362.  
  363.     window = FrontWindow();    /* we only adjust the cursor when we are in front */
  364.     if ( (! gInBackground) && (! IsDAWindow(window)) ) {
  365.         /* calculate regions for different cursor shapes */
  366.         arrowRgn = NewRgn();
  367.         iBeamRgn = NewRgn();
  368.  
  369.         /* start arrowRgn wide open */
  370.         SetRectRgn(arrowRgn, kExtremeNeg, kExtremeNeg, kExtremePos, kExtremePos);
  371.  
  372.         /* calculate iBeamRgn */
  373.         if ( IsAppWindow(window) ) {
  374.             iBeamRect = (*((DocumentPeek) window)->docTE)->viewRect;
  375.             SetPort(window);    /* make a global version of the viewRect */
  376.             LocalToGlobal(&TopLeft(iBeamRect));
  377.             LocalToGlobal(&BotRight(iBeamRect));
  378.             RectRgn(iBeamRgn, &iBeamRect);
  379.             /* we temporarily change the port’s origin to “globalfy” the visRgn */
  380.             SetOrigin(-window->portBits.bounds.left, -window->portBits.bounds.top);
  381.             SectRgn(iBeamRgn, window->visRgn, iBeamRgn);
  382.             SetOrigin(0, 0);
  383.         }
  384.  
  385.         /* subtract other regions from arrowRgn */
  386.         DiffRgn(arrowRgn, iBeamRgn, arrowRgn);
  387.  
  388.         /* change the cursor and the region parameter */
  389.         if ( PtInRgn(mouse, iBeamRgn) ) {
  390.             SetCursor(*GetCursor(iBeamCursor));
  391.             CopyRgn(iBeamRgn, region);
  392.         } else {
  393.             SetCursor(&qd.arrow);
  394.             CopyRgn(arrowRgn, region);
  395.         }
  396.  
  397.         DisposeRgn(arrowRgn);
  398.         DisposeRgn(iBeamRgn);
  399.     }
  400. } /*AdjustCursor*/
  401.  
  402.  
  403. /*    Get the global coordinates of the mouse. When you call OSEventAvail
  404.     it will return either a pending event or a null event. In either case,
  405.     the where field of the event record will contain the current position
  406.     of the mouse in global coordinates and the modifiers field will reflect
  407.     the current state of the modifiers. Another way to get the global
  408.     coordinates is to call GetMouse and LocalToGlobal, but that requires
  409.     being sure that thePort is set to a valid port. */
  410.  
  411. #pragma segment Main
  412. void GetGlobalMouse( Point *mouse )
  413. {
  414.     EventRecord    event;
  415.     
  416.     OSEventAvail(kNoEvents, &event);    /* we aren't interested in any events */
  417.     *mouse = event.where;                /* just the mouse position */
  418. } /*GetGlobalMouse*/
  419.  
  420.  
  421. /*    Called when a mouseDown occurs in the grow box of an active window. In
  422.     order to eliminate any 'flicker', we want to invalidate only what is
  423.     necessary. Since ResizeWindow invalidates the whole portRect, we save
  424.     the old TE viewRect, intersect it with the new TE viewRect, and
  425.     remove the result from the update region. However, we must make sure
  426.     that any old update region that might have been around gets put back. */
  427.  
  428. #pragma segment Main
  429. void DoGrowWindow( WindowPtr window, EventRecord *event )
  430. {
  431.     long        growResult;
  432.     Rect        tempRect;
  433.     RgnHandle    tempRgn;
  434.     DocumentPeek doc;
  435.     
  436.     tempRect = qd.screenBits.bounds;                    /* set up limiting values */
  437.     tempRect.left = kMinDocDim;
  438.     tempRect.top = kMinDocDim;
  439.     growResult = GrowWindow(window, event->where, &tempRect);
  440.     /* see if it really changed size */
  441.     if ( growResult != 0 ) {
  442.         doc = (DocumentPeek) window;
  443.         tempRect = (*doc->docTE)->viewRect;                /* save old text box */
  444.         tempRgn = NewRgn();
  445.         GetLocalUpdateRgn(window, tempRgn);                /* get localized update region */
  446.         SizeWindow(window, LoWrd(growResult), HiWrd(growResult), true);
  447.         ResizeWindow(window);
  448.         /* calculate & validate the region that hasn’t changed so it won’t get redrawn */
  449.         SectRect(&tempRect, &(*doc->docTE)->viewRect, &tempRect);
  450.         ValidRect(&tempRect);                            /* take it out of update */
  451.         InvalRgn(tempRgn);                                /* put back any prior update */
  452.         DisposeRgn(tempRgn);
  453.     }
  454. } /* DoGrowWindow */
  455.  
  456.  
  457. /*     Called when a mouseClick occurs in the zoom box of an active window.
  458.     Everything has to get re-drawn here, so we don't mind that
  459.     ResizeWindow invalidates the whole portRect. */
  460.  
  461. #pragma segment Main
  462. void DoZoomWindow( WindowPtr window, short part )
  463. {
  464.     EraseRect(&window->portRect);
  465.     ZoomWindow(window, part, window == FrontWindow());
  466.     ResizeWindow(window);
  467. } /*  DoZoomWindow */
  468.  
  469.  
  470. /* Called when the window has been resized to fix up the controls and content. */
  471. #pragma segment Main
  472. void ResizeWindow( WindowPtr window )
  473. {
  474.     AdjustScrollbars(window, true);
  475.     AdjustTE(window);
  476.     InvalRect(&window->portRect);
  477. } /* ResizeWindow */
  478.  
  479.  
  480. /* Returns the update region in local coordinates */
  481. #pragma segment Main
  482. void GetLocalUpdateRgn( WindowPtr window, RgnHandle localRgn )
  483. {
  484.     CopyRgn(((WindowPeek) window)->updateRgn, localRgn);    /* save old update region */
  485.     OffsetRgn(localRgn, window->portBits.bounds.left, window->portBits.bounds.top);
  486. } /* GetLocalUpdateRgn */
  487.  
  488.  
  489. /*    This is called when an update event is received for a window.
  490.     It calls DrawWindow to draw the contents of an application window.
  491.     As an efficiency measure that does not have to be followed, it
  492.     calls the drawing routine only if the visRgn is non-empty. This
  493.     will handle situations where calculations for drawing or drawing
  494.     itself is very time-consuming. */
  495.  
  496. #pragma segment Main
  497. void DoUpdate( WindowPtr window )
  498. {
  499.     if ( IsAppWindow(window) ) {
  500.         BeginUpdate(window);                /* this sets up the visRgn */
  501.         if ( ! EmptyRgn(window->visRgn) )    /* draw if updating needs to be done */
  502.             DrawWindow(window);
  503.         EndUpdate(window);
  504.     }
  505. } /*DoUpdate*/
  506.  
  507.  
  508. /*    This is called when a window is activated or deactivated.
  509.     It calls TextEdit to deal with the selection. */
  510.  
  511. #pragma segment Main
  512. void DoActivate( WindowPtr window, Boolean becomingActive )
  513. {
  514.     RgnHandle    tempRgn, clipRgn;
  515.     Rect        growRect;
  516.     DocumentPeek doc;
  517.     
  518.     if ( IsAppWindow(window) ) {
  519.         doc = (DocumentPeek) window;
  520.         if ( becomingActive ) {
  521.             /*    since we don’t want TEActivate to draw a selection in an area where
  522.                 we’re going to erase and redraw, we’ll clip out the update region
  523.                 before calling it. */
  524.             tempRgn = NewRgn();
  525.             clipRgn = NewRgn();
  526.             GetLocalUpdateRgn(window, tempRgn);            /* get localized update region */
  527.             GetClip(clipRgn);
  528.             DiffRgn(clipRgn, tempRgn, tempRgn);            /* subtract updateRgn from clipRgn */
  529.             SetClip(tempRgn);
  530.             TEActivate(doc->docTE);
  531.             SetClip(clipRgn);                            /* restore the full-blown clipRgn */
  532.             DisposeRgn(tempRgn);
  533.             DisposeRgn(clipRgn);
  534.             
  535.             /* the controls must be redrawn on activation: */
  536.             (*doc->docVScroll)->contrlVis = kControlVisible;
  537.             (*doc->docHScroll)->contrlVis = kControlVisible;
  538.             InvalRect(&(*doc->docVScroll)->contrlRect);
  539.             InvalRect(&(*doc->docHScroll)->contrlRect);
  540.             /* the growbox needs to be redrawn on activation: */
  541.             growRect = window->portRect;
  542.             /* adjust for the scrollbars */
  543.             growRect.top = (short) (growRect.bottom - kScrollbarAdjust);
  544.             growRect.left = (short) (growRect.right - kScrollbarAdjust);
  545.             InvalRect(&growRect);
  546.         }
  547.         else {        
  548.             TEDeactivate(doc->docTE);
  549.             /* the controls must be hidden on deactivation: */
  550.             HideControl(doc->docVScroll);
  551.             HideControl(doc->docHScroll);
  552.             /* the growbox should be changed immediately on deactivation: */
  553.             DrawGrowIcon(window);
  554.         }
  555.     }
  556. } /*DoActivate*/
  557.  
  558.  
  559. /*    This is called when a mouseDown occurs in the content of a window. */
  560.  
  561. #pragma segment Main
  562. void DoContentClick( WindowPtr window, EventRecord *event )
  563. {
  564.     Point        mouse;
  565.     ControlHandle control;
  566.     short        part, value;
  567.     Boolean        shiftDown;
  568.     DocumentPeek doc;
  569.     Rect        teRect;
  570.     long        multiClicks;
  571.     short        charOffset;
  572.     short         theLine;
  573.  
  574.     multiClicks = TrackMultipleClicks(event->when, event->where);
  575.     
  576.     if ( IsAppWindow(window) ) {
  577.         SetPort(window);
  578.         mouse = event->where;                            /* get the click position */
  579.         GlobalToLocal(&mouse);
  580.         doc = (DocumentPeek) window;
  581.         /* see if we are in the viewRect. if so, we won’t check the controls */
  582.         GetTERect(window, &teRect);
  583.         if ( PtInRect(mouse, &teRect) ) {
  584.             /* see if we need to extend the selection */
  585.             shiftDown = (event->modifiers & shiftKey) != 0;    /* extend if Shift is down */
  586.                 
  587.             if (shiftDown || multiClicks < 3)            /* let TextEdit handle hard ones */
  588.                 TEClick(mouse, shiftDown, doc->docTE);
  589.             else                                        /* SPEECH MANAGER:  we do the easier ones */
  590.             {
  591.                 if (multiClicks == 3)                    /* triple-click: select entire line */
  592.                 {
  593.                     charOffset = TEGetOffset(mouse, doc->docTE);
  594.                     
  595.                     theLine = TECharOffsetToLine(doc->docTE, charOffset);
  596.     
  597.                     if (theLine == (*(doc->docTE))->nLines)    /* special case for beyond end of text */
  598.                         theLine--;
  599.                     
  600.                     TESelectLine(doc->docTE, theLine);
  601.                 }
  602.                 else if (multiClicks == 4)                /* quadruple-click: select it all */
  603.                     TESetSelect(0, 32767, doc->docTE);
  604.             }
  605.         } else {
  606.             part = FindControl(mouse, window, &control);
  607.             switch ( part ) {
  608.                 case 0:                            /* do nothing for viewRect case */
  609.                     break;
  610.                 case inThumb:
  611.                     value = GetCtlValue(control);
  612.                     part = TrackControl(control, mouse, nil);
  613.                     if ( part != 0 ) {
  614.                         value -= GetCtlValue(control);
  615.                         /* value now has CHANGE in value; if value changed, scroll */
  616.                         if ( value != 0 )
  617.                             if ( control == doc->docVScroll )
  618.                                 TEScroll(0, value * (*doc->docTE)->lineHeight, doc->docTE);
  619.                             else
  620.                                 TEScroll(value, 0, doc->docTE);
  621.                     }
  622.                     break;
  623.                 default:                        /* they clicked in an arrow, so track & scroll */
  624.                     if ( control == doc->docVScroll )
  625.                         value = TrackControl(control, mouse, (ProcPtr) VActionProc);
  626.                     else
  627.                         value = TrackControl(control, mouse, (ProcPtr) HActionProc);
  628.                     break;
  629.             }
  630.         }
  631.     }
  632. } /*DoContentClick*/
  633.  
  634.  
  635. /* This is called for any keyDown or autoKey events, except when the
  636.  Command key is held down. It looks at the frontmost window to decide what
  637.  to do with the key typed. */
  638.  
  639. #pragma segment Main
  640. void DoKeyDown( EventRecord *event )
  641. {
  642.     WindowPtr    window;
  643.     unsigned char key;
  644.     TEHandle    te;
  645.     short        sIndex, eIndex;
  646.     short        theLine;
  647.     OSErr        err;
  648.  
  649.     window = FrontWindow();
  650.     if ( IsAppWindow(window) ) {
  651.         te = ((DocumentPeek) window)->docTE;
  652.         key = (unsigned char) event->message & charCodeMask;
  653.  
  654.         if ( key == kEnterChar ) {
  655.             /* SPEECH MANAGER: */
  656.             /* If any text selected, speak it.  Otherwise speak entire line. */
  657.  
  658.             sIndex = (*te)->selStart;
  659.             eIndex = (*te)->selEnd;
  660.         
  661.             if (eIndex <= sIndex)            /* nothing selected */
  662.             {                                /* speak entire line insertion point is on */
  663.                 theLine = TECharOffsetToLine(te, sIndex);
  664.  
  665.                 if (theLine == (*te)->nLines)    /* special case for beyond end of text */
  666.                     theLine--;
  667.  
  668.                 sIndex = TELineStartOffset(te, theLine);
  669.                 eIndex = TELineStartOffset(te, theLine + 1);
  670.             }
  671.                 
  672.             err = SpeakTextRange(te, sIndex, eIndex);
  673.         }
  674.         else if ( key == kDelChar ||
  675.                 (*te)->teLength - ((*te)->selEnd - (*te)->selStart) + 1 < kMaxTELength ) 
  676.         {
  677.             /* we have a char. for our window; see if we are still below TextEdit’s
  678.                 limit for the number of characters (but deletes are always rad) */
  679.  
  680.             TEKey(key, te);
  681.             AdjustScrollbars(window, false);
  682.             AdjustTE(window);
  683.         } 
  684.         else
  685.             AlertUser(eExceedChar);
  686.     }
  687. } /*DoKeyDown*/
  688.  
  689.  
  690. /*    Calculate a sleep value for WaitNextEvent. This takes into account the things
  691.     that DoIdle does with idle time. */
  692.  
  693. #pragma segment Main
  694. unsigned long GetSleep( void )
  695. {
  696.     long        sleep;
  697.     WindowPtr    window;
  698.     TEHandle    te;
  699.  
  700.     sleep = MAXLONG;                        /* default value for sleep */
  701.     if ( !gInBackground ) {
  702.         window = FrontWindow();            /* and the front window is ours... */
  703.         if ( IsAppWindow(window) ) {
  704.             te = ((DocumentPeek) (window))->docTE;    /* and the selection is an insertion point... */
  705.             if ( (*te)->selStart == (*te)->selEnd )
  706.                 sleep = GetCaretTime();        /* blink time for the insertion point */
  707.         }
  708.     }
  709.     return sleep;
  710. } /*GetSleep*/
  711.  
  712.  
  713. /*    Common algorithm for pinning the value of a control. It returns the actual amount
  714.     the value of the control changed. Note the pinning is done for the sake of returning
  715.     the amount the control value changed. */
  716.  
  717. #pragma segment Main
  718. void CommonAction( ControlHandle control, short *amount )
  719. {
  720.     short        value, max;
  721.     
  722.     value = GetCtlValue(control);    /* get current value */
  723.     max = GetCtlMax(control);        /* and maximum value */
  724.     *amount = (short) (value - *amount);
  725.     if ( *amount < 0 )
  726.         *amount = 0;
  727.     else if ( *amount > max )
  728.         *amount = max;
  729.     SetCtlValue(control, *amount);
  730.     *amount = (short) (value - *amount);        /* calculate the real change */
  731. } /* CommonAction */
  732.  
  733.  
  734. /* Determines how much to change the value of the vertical scrollbar by and how
  735.     much to scroll the TE record. */
  736.  
  737. #pragma segment Main
  738. pascal void VActionProc( ControlHandle control, short part )
  739. {
  740.     short        amount;
  741.     WindowPtr    window;
  742.     TEPtr        te;
  743.     
  744.     if ( part != 0 ) {                /* if it was actually in the control */
  745.         window = (*control)->contrlOwner;
  746.         te = *((DocumentPeek) window)->docTE;
  747.         switch ( part ) {
  748.             case inUpButton:
  749.             case inDownButton:        /* one line */
  750.                 amount = 1;
  751.                 break;
  752.             case inPageUp:            /* one page */
  753.             case inPageDown:
  754.                 amount = (short) (te->viewRect.bottom - te->viewRect.top) / te->lineHeight;
  755.                 break;
  756.         }
  757.         if ( (part == inDownButton) || (part == inPageDown) )
  758.             amount = (short) -amount;        /* reverse direction for a downer */
  759.         CommonAction(control, &amount);
  760.         if ( amount != 0 )
  761.             TEScroll(0, amount * te->lineHeight, ((DocumentPeek) window)->docTE);
  762.     }
  763. } /* VActionProc */
  764.  
  765.  
  766. /* Determines how much to change the value of the horizontal scrollbar by and how
  767. much to scroll the TE record. */
  768.  
  769. #pragma segment Main
  770. pascal void HActionProc( ControlHandle control, short part )
  771. {
  772.     short        amount;
  773.     WindowPtr    window;
  774.     TEPtr        te;
  775.     
  776.     if ( part != 0 ) {
  777.         window = (*control)->contrlOwner;
  778.         te = *((DocumentPeek) window)->docTE;
  779.         switch ( part ) {
  780.             case inUpButton:
  781.             case inDownButton:        /* a few pixels */
  782.                 amount = kButtonScroll;
  783.                 break;
  784.             case inPageUp:            /* a page */
  785.             case inPageDown:
  786.                 amount = (short) (te->viewRect.right - te->viewRect.left);
  787.                 break;
  788.         }
  789.         if ( (part == inDownButton) || (part == inPageDown) )
  790.             amount = (short) -amount;        /* reverse direction */
  791.         CommonAction(control, &amount);
  792.         if ( amount != 0 )
  793.             TEScroll(amount, 0, ((DocumentPeek) window)->docTE);
  794.     }
  795. } /* VActionProc */
  796.  
  797.  
  798. /* This is called whenever we get a null event et al.
  799.  It takes care of necessary periodic actions. For this program, it calls TEIdle. */
  800.  
  801. #pragma segment Main
  802. void DoIdle( void )
  803. {
  804.     WindowPtr    window;
  805.  
  806.     window = FrontWindow();
  807.     if ( IsAppWindow(window) )
  808.         TEIdle(((DocumentPeek) window)->docTE);
  809. } /*DoIdle*/
  810.  
  811.  
  812. /* Draw the contents of an application window. */
  813.  
  814. #pragma segment Main
  815. void DrawWindow( WindowPtr window )
  816. {
  817.     SetPort(window);
  818.     EraseRect(&window->portRect);
  819.     DrawControls(window);
  820.     DrawGrowIcon(window);
  821.     TEUpdate(&window->portRect, ((DocumentPeek) window)->docTE);
  822. } /*DrawWindow*/
  823.  
  824.  
  825. /*    Enable and disable menus based on the current state.
  826.     The user can only select enabled menu items. We set up all the menu items
  827.     before calling MenuSelect or MenuKey, since these are the only times that
  828.     a menu item can be selected. Note that MenuSelect is also the only time
  829.     the user will see menu items. This approach to deciding what enable/
  830.     disable state a menu item has the advantage of concentrating all
  831.     the decision-making in one routine, as opposed to being spread throughout
  832.     the application. Other application designs may take a different approach
  833.     that may or may not be as valid. */
  834.  
  835. #pragma segment Main
  836. void AdjustMenus( void )
  837. {
  838.     WindowPtr    window;
  839.     MenuHandle    menu;
  840.     long        offset;
  841.     Boolean        undo;
  842.     Boolean        cutCopyClear;
  843.     Boolean        paste;
  844.     TEHandle    te;
  845.  
  846.     window = FrontWindow();
  847.  
  848.     menu = GetMHandle(mFile);
  849.     if ( gNumDocuments < kMaxOpenDocuments )
  850.     {
  851.         EnableItem(menu, iNew);        /* New is enabled when we can open more documents */
  852.         EnableItem(menu, iOpen);    /* Open is enabled when we can open more documents */
  853.     }
  854.     else
  855.     {
  856.         DisableItem(menu, iNew);
  857.         DisableItem(menu, iOpen);
  858.     }
  859.     if ( window != nil )            /* Close is enabled when there is a window to close */
  860.         EnableItem(menu, iClose);
  861.     else
  862.         DisableItem(menu, iClose);
  863.  
  864.     menu = GetMHandle(mEdit);
  865.     undo = false;
  866.     cutCopyClear = false;
  867.     paste = false;
  868.     if ( IsDAWindow(window) ) {
  869.         undo = true;                /* all editing is enabled for DA windows */
  870.         cutCopyClear = true;
  871.         paste = true;
  872.         
  873.         DisableItem(menu, iSelectAll);
  874.     } else if ( IsAppWindow(window) ) {
  875.         te = ((DocumentPeek) window)->docTE;
  876.         if ( (*te)->selStart < (*te)->selEnd )
  877.             cutCopyClear = true;
  878.             /* Cut, Copy, and Clear is enabled for app. windows with selections */
  879.         if ( GetScrap(nil, 'TEXT', &offset)  > 0)
  880.             paste = true;            /* if there’s any text in the clipboard, paste is enabled */
  881.  
  882.         EnableItem(menu, iSelectAll);        
  883.     }
  884.     
  885.     if ( undo )
  886.         EnableItem(menu, iUndo);
  887.     else
  888.         DisableItem(menu, iUndo);
  889.         
  890.     if ( cutCopyClear ) {
  891.         EnableItem(menu, iCut);
  892.         EnableItem(menu, iCopy);
  893.         EnableItem(menu, iClear);
  894.     } else {
  895.         DisableItem(menu, iCut);
  896.         DisableItem(menu, iCopy);
  897.         DisableItem(menu, iClear);
  898.     }
  899.     
  900.     if ( paste )
  901.         EnableItem(menu, iPaste);
  902.     else
  903.         DisableItem(menu, iPaste);
  904. } /*AdjustMenus*/
  905.  
  906.  
  907. /*    This is called when an item is chosen from the menu bar (after calling
  908.     MenuSelect or MenuKey). It does the right thing for each command. */
  909.  
  910. #pragma segment Main
  911. void DoMenuCommand( long menuResult )
  912. {
  913.     short        menuID, menuItem;
  914.     short        itemHit, daRefNum;
  915.     Str255        daName;
  916.     OSErr        saveErr;
  917.     TEHandle    te;
  918.     WindowPtr    window;
  919.     Handle        aHandle;
  920.     long        oldSize, newSize;
  921.     long        total, contig;
  922.     short        sIndex, eIndex;
  923.     short        theLine;
  924.     OSErr        err;
  925.     
  926.     window = FrontWindow();
  927.     menuID = HiWord(menuResult);    /* use macros for efficiency to... */
  928.     menuItem = LoWord(menuResult);    /* get menu item number and menu number */
  929.     switch ( menuID ) {
  930.         case mApple:
  931.             switch ( menuItem ) {
  932.                 case iAbout:        /* bring up alert for About */
  933.                     itemHit = Alert(rAboutAlert, nil);
  934.                     break;
  935.                 default:            /* all non-About items in this menu are DAs et al */
  936.                     /* type Str255 is an array in MPW 3 */
  937.                     GetItem(GetMHandle(mApple), menuItem, daName);
  938.                     daRefNum = OpenDeskAcc(daName);
  939.                     break;
  940.             }
  941.             break;
  942.         case mFile:
  943.             switch ( menuItem ) {
  944.                 case iNew:
  945.                     (void) DoNew();
  946.                     break;
  947.                 case iOpen:
  948.                     DoOpen();
  949.                     break;
  950.                 case iClose:
  951.                     DoCloseWindow(FrontWindow());            /* ignore the result */
  952.                     break;
  953.                 case iQuit:
  954.                     Terminate();
  955.                     break;
  956.             }
  957.             break;
  958.         case mEdit:                    /* call SystemEdit for DA editing & MultiFinder */
  959.             if ( !SystemEdit(menuItem-1) ) {
  960.                 te = ((DocumentPeek) FrontWindow())->docTE;
  961.                 switch ( menuItem ) {
  962.                     case iCut:
  963.                         if ( ZeroScrap() == noErr ) {
  964.                             PurgeSpace(&total, &contig);
  965.                             if ((*te)->selEnd - (*te)->selStart + kTESlop > contig)
  966.                                 AlertUser(eNoSpaceCut);
  967.                             else 
  968.                                 {
  969.                                 TECut(te);
  970.                                 if ( TEToScrap() != noErr ) {
  971.                                     AlertUser(eNoCut);
  972.                                     ZeroScrap();
  973.                                 }
  974.                             }
  975.                         }
  976.                         break;
  977.                     case iCopy:
  978.                         if ( ZeroScrap() == noErr ) {
  979.                             TECopy(te);    /* after copying, export the TE scrap */
  980.                             if ( TEToScrap() != noErr ) {
  981.                                 AlertUser(eNoCopy);
  982.                                 ZeroScrap();
  983.                             }
  984.                         }
  985.                         break;
  986.                     case iPaste:    /* import the TE scrap before pasting */
  987.                         if ( TEFromScrap() == noErr ) {
  988.                             if ( TEGetScrapLen() + ((*te)->teLength -
  989.                                 ((*te)->selEnd - (*te)->selStart)) > kMaxTELength )
  990.                                 AlertUser(eExceedPaste);
  991.                             else {
  992.                                 aHandle = (Handle) TEGetText(te);
  993.                                 oldSize = GetHandleSize(aHandle);
  994.                                 newSize = oldSize + TEGetScrapLen() + kTESlop;
  995.                                 SetHandleSize(aHandle, newSize);
  996.                                 saveErr = MemError();
  997.                                 SetHandleSize(aHandle, oldSize);
  998.                                 if (saveErr != noErr)
  999.                                     AlertUser(eNoSpacePaste);
  1000.                                 else
  1001.                                     TEPaste(te);
  1002.                             }
  1003.                         }
  1004.                         else
  1005.                             AlertUser(eNoPaste);
  1006.                         break;
  1007.                     case iClear:
  1008.                         TEDelete(te);
  1009.                         break;
  1010.                     case iSelectAll:
  1011.                         TESetSelect(0, 32767, te);
  1012.                         break;
  1013.                 }
  1014.             AdjustScrollbars(window, false);
  1015.             AdjustTE(window);
  1016.             }
  1017.             break;
  1018.         case mSpeech:                            /* SPEECH MANAGER */
  1019.             te = ((DocumentPeek) FrontWindow())->docTE;
  1020.             
  1021.             switch ( menuItem ) {
  1022.                 case iSpeakAll: /* If any text selected, speak it.  Otherwise speak whole text record. */
  1023.                     sIndex = (*te)->selStart;
  1024.                     eIndex = (*te)->selEnd;
  1025.                     
  1026.                     if (eIndex <= sIndex)                /* no text is currently selected */
  1027.                     {
  1028.                         sIndex = 0;
  1029.                         eIndex = (*te)->teLength;
  1030.                     }
  1031.                     
  1032.                     saveErr = SpeakTextRange(te, sIndex, eIndex);
  1033.                     break;
  1034.  
  1035.                 case iSpeakLine: /* If any text selected, speak it.  Otherwise speak entire line. */
  1036.         
  1037.                     sIndex = (*te)->selStart;
  1038.                     eIndex = (*te)->selEnd;
  1039.                 
  1040.                     if (eIndex <= sIndex)            /* nothing selected */
  1041.                     {                                /* speak entire line insertion point is on */
  1042.                         theLine = TECharOffsetToLine(te, sIndex);
  1043.         
  1044.                         if (theLine == (*te)->nLines) /* special case for beyond end of text */
  1045.                             theLine--;
  1046.  
  1047.                         sIndex = TELineStartOffset(te, theLine);
  1048.                         eIndex = TELineStartOffset(te, theLine + 1);
  1049.                     }
  1050.                         
  1051.                     saveErr = SpeakTextRange(te, sIndex, eIndex);                    
  1052.                     break;
  1053.                     
  1054.                 case iPauseSpeech:
  1055.                     if (gSpeechChan)
  1056.                         saveErr = PauseSpeechAt(gSpeechChan, kImmediate);
  1057.                     break;
  1058.                     
  1059.                 case iContinueSpeech:
  1060.                     if (gSpeechChan)
  1061.                         saveErr = ContinueSpeech(gSpeechChan);
  1062.                     break;
  1063.                 }
  1064.             break;
  1065.  
  1066.  
  1067.         case mVoice:                            /* SPEECH MANAGER */
  1068.             if (menuItem)
  1069.                 {
  1070.                 if (gSpeechChan)
  1071.                     {
  1072.                         err = DisposeSpeechChannel(gSpeechChan);
  1073.                         gSpeechChan = NULL;
  1074.                     }
  1075.                 voiceSel = menuItem-1;
  1076.                 }
  1077.             break;
  1078.     }
  1079.     HiliteMenu(0);                    /* unhighlight what MenuSelect (or MenuKey) hilited */
  1080. } /*DoMenuCommand*/
  1081.  
  1082.  
  1083.  
  1084.  
  1085.  
  1086. /* Create a new document and window. */
  1087.  
  1088. #pragma segment Main
  1089. Boolean DoNew( void )
  1090. {
  1091.     Boolean        good = false;
  1092.     Ptr            storage;
  1093.     WindowPtr    window;
  1094.     Rect        destRect, viewRect;
  1095.     DocumentPeek doc;
  1096.  
  1097.     storage = NewPtr(sizeof(DocumentRecord));
  1098.     if ( storage != nil ) {
  1099.         window = GetNewWindow(rDocWindow, storage, (WindowPtr) -1);
  1100.         if ( window != nil ) {
  1101.             gNumDocuments += 1;            /* this will be decremented when we call DoCloseWindow */
  1102.             SetPort(window);
  1103.             doc =  (DocumentPeek) window;
  1104.             GetTERect(window, &viewRect);
  1105.             destRect = viewRect;
  1106.             destRect.right = (short) (destRect.left + kMaxDocWidth);
  1107.             doc->docTE = TENew(&destRect, &viewRect);
  1108.             good = doc->docTE != nil;    /* if TENew succeeded, we have a good document */
  1109.             if ( good ) {                /* 1.02 - good document? — proceed */
  1110.                 AdjustViewRect(doc->docTE);
  1111.                 TEAutoView(true, doc->docTE);
  1112.                 doc->docClik = (ProcPtr) (*doc->docTE)->clikLoop;
  1113.                 (*doc->docTE)->clikLoop = (ClikLoopProcPtr) ASMCLIKLOOP;
  1114.             }
  1115.             
  1116.             if ( good ) {                /* good document? — get scrollbars */
  1117.                 doc->docVScroll = GetNewControl(rVScroll, window);
  1118.                 good = (doc->docVScroll != nil);
  1119.             }
  1120.             if ( good) {
  1121.                 doc->docHScroll = GetNewControl(rHScroll, window);
  1122.                 good = (doc->docHScroll != nil);
  1123.             }
  1124.             
  1125.             if ( good ) {                /* good? — adjust & draw the controls, draw the window */
  1126.                 /* false to AdjustScrollValues means musn’t redraw; technically, of course,
  1127.                 the window is hidden so it wouldn’t matter whether we called ShowControl or not. */
  1128.                 AdjustScrollValues(window, false);
  1129.                 ShowWindow(window);
  1130.             } else {
  1131.                 DoCloseWindow(window);    /* otherwise regret we ever created it... */
  1132.                 AlertUser(eNoWindow);            /* and tell user */
  1133.             }
  1134.         } else
  1135.             DisposPtr(storage);            /* get rid of the storage if it is never used */
  1136.     }
  1137.     
  1138.     return good;
  1139.     
  1140. } /*DoNew*/
  1141.  
  1142. /* Open a document into a new window. */
  1143.  
  1144. #pragma segment Main
  1145. void DoOpen( void )
  1146. {
  1147.     SFReply            theReply;
  1148.     Point             where = {20, 90};
  1149.     SFTypeList        typeList = {'TEXT'};
  1150.     OSErr            err;
  1151.     short            fRefNum;
  1152.     long             fileLen;
  1153.     Handle            textHandle;
  1154.     DocumentPeek    doc;
  1155.     
  1156.     SFGetFile(where, 0, 0, 1, typeList, 0, &theReply); /* get a text file */
  1157.     
  1158.     if (theReply.good)
  1159.     {
  1160.         err = FSOpen(theReply.fName, theReply.vRefNum, &fRefNum); /* Open the file */
  1161.         if (err)                                /* failed on open */
  1162.         {
  1163.             SysBeep(10);                    /* bomb-out */
  1164.         }
  1165.         else
  1166.         {
  1167.             err = GetEOF(fRefNum, &fileLen);    /* find out how long file is */
  1168.             if (err) { SysBeep(10); }
  1169.             
  1170.             if (fileLen > kMaxTELength)        /* limit to max len of TE Record */
  1171.                 fileLen = kMaxTELength;
  1172.                 
  1173.             textHandle = NewHandle(fileLen); /* get some memory to hold text */
  1174.             if (!textHandle) { SysBeep(10); }
  1175.             
  1176.             MoveHHi(textHandle);
  1177.             HLock(textHandle);
  1178.             
  1179.             err = FSRead(fRefNum, &fileLen, *textHandle); /* read in the text */
  1180.             if (err) { SysBeep(10); }
  1181.             
  1182.             if (DoNew())                    /* was able to make a new window */
  1183.             {
  1184.                 doc =  (DocumentPeek) FrontWindow();
  1185.                 TESetText(*textHandle, fileLen, doc->docTE); /* stuff text in TERecord */
  1186.             }
  1187.             else { SysBeep(10); }
  1188.             
  1189.             DisposeHandle(textHandle);
  1190.             
  1191.             FSClose(fRefNum);                /* close the disk file */
  1192.         }
  1193.     }
  1194. }
  1195.  
  1196. /* Close a window. This handles desk accessory and application windows. */
  1197.  
  1198. /*    1.01 - At this point, if there was a document associated with a
  1199.     window, you could do any document saving processing if it is 'dirty'.
  1200.     DoCloseWindow would return true if the window actually closed, i.e.,
  1201.     the user didn’t cancel from a save dialog. This result is handy when
  1202.     the user quits an application, but then cancels the save of a document
  1203.     associated with a window. */
  1204.  
  1205. #pragma segment Main
  1206. Boolean DoCloseWindow( WindowPtr window )
  1207. {
  1208.     TEHandle    te;
  1209.  
  1210.     if ( IsDAWindow(window) )
  1211.         CloseDeskAcc(((WindowPeek) window)->windowKind);
  1212.     else if ( IsAppWindow(window) ) {
  1213.         te = ((DocumentPeek) window)->docTE;
  1214.         if ( te != nil )
  1215.             TEDispose(te);            /* dispose the TEHandle if we got far enough to make one */
  1216.         /*    1.01 - We used to call DisposeWindow, but that was technically
  1217.             incorrect, even though we allocated storage for the window on
  1218.             the heap. We should instead call CloseWindow to have the structures
  1219.             taken care of and then dispose of the storage ourselves. */
  1220.         CloseWindow(window);
  1221.         DisposPtr((Ptr) window);
  1222.         gNumDocuments -= 1;
  1223.     }
  1224.     return true;
  1225. } /*DoCloseWindow*/
  1226.  
  1227.  
  1228. /**************************************************************************************
  1229. *** 1.01 DoCloseBehind(window) was removed ***
  1230.  
  1231.     1.01 - DoCloseBehind was a good idea for closing windows when quitting
  1232.     and not having to worry about updating the windows, but it suffered
  1233.     from a fatal flaw. If a desk accessory owned two windows, it would
  1234.     close both those windows when CloseDeskAcc was called. When DoCloseBehind
  1235.     got around to calling DoCloseWindow for that other window that was already
  1236.     closed, things would go very poorly. Another option would be to have a
  1237.     procedure, GetRearWindow, that would go through the window list and return
  1238.     the last window. Instead, we decided to present the standard approach
  1239.     of getting and closing FrontWindow until FrontWindow returns NIL. This
  1240.     has a potential benefit in that the window whose document needs to be saved
  1241.     may be visible since it is the front window, therefore decreasing the
  1242.     chance of user confusion. For aesthetic reasons, the windows in the
  1243.     application should be checked for updates periodically and have the
  1244.     updates serviced.
  1245. **************************************************************************************/
  1246.  
  1247.  
  1248. /* Clean up the application and exit. We close all of the windows so that
  1249.  they can update their documents, if any. */
  1250.  
  1251. /*    1.01 - If we find out that a cancel has occurred, we won't exit to the
  1252.     shell, but will return instead. */
  1253.  
  1254. #pragma segment Main
  1255. void Terminate( void )
  1256. {
  1257.     WindowPtr    aWindow;
  1258.     Boolean        closed;
  1259.     OSErr        err;
  1260.     
  1261.     closed = true;
  1262.     do {
  1263.         aWindow = FrontWindow();                /* get the current front window */
  1264.         if (aWindow != nil)
  1265.             closed = DoCloseWindow(aWindow);    /* close this window */    
  1266.     }
  1267.     while (closed && (aWindow != nil));
  1268.     if (closed)
  1269.     {
  1270.         if (gSpeechChan)                        /* SPEECH MANAGER: get rid of channel */
  1271.         {
  1272.             err = DisposeSpeechChannel(gSpeechChan);
  1273.             
  1274.             if (err != noErr)
  1275.                 AlertUser(eSpeechManager);        /* some kind of error */
  1276.         }
  1277.  
  1278.         ExitToShell();                            /* exit if no cancellation */
  1279.     }
  1280. } /*Terminate*/
  1281.  
  1282.  
  1283. /*    Set up the whole world, including global variables, Toolbox managers,
  1284.     menus, and a single blank document. */
  1285.  
  1286. /*    1.01 - The code that used to be part of ForceEnvirons has been moved into
  1287.     this module. If an error is detected, instead of merely doing an ExitToShell,
  1288.     which leaves the user without much to go on, we call AlertUser, which puts
  1289.     up a simple alert that just says an error occurred and then calls ExitToShell.
  1290.     Since there is no other cleanup needed at this point if an error is detected,
  1291.     this form of error- handling is acceptable. If more sophisticated error recovery
  1292.     is needed, an exception mechanism, such as is provided by Signals, can be used. */
  1293.  
  1294. #pragma segment Initialize
  1295. void Initialize( void )
  1296. {
  1297.     long        total, contig;
  1298.     EventRecord event;
  1299.     short        count;
  1300.  
  1301.     gInBackground = false;
  1302.  
  1303.     InitGraf((Ptr) &qd.thePort);
  1304.     InitFonts();
  1305.     InitWindows();
  1306.     InitMenus();
  1307.     TEInit();
  1308.     InitDialogs(nil);
  1309.     InitCursor();
  1310.  
  1311.     /*    Call MPPOpen and ATPLoad at this point to initialize AppleTalk,
  1312.          if you are using it. */
  1313.     /*    NOTE -- It is no longer necessary, and actually unhealthy, to check
  1314.         PortBUse and SPConfig before opening AppleTalk. The drivers are capable
  1315.         of checking for port availability themselves. */
  1316.     
  1317.     /*    This next bit of code is necessary to allow the default button of our
  1318.         alert be outlined.
  1319.         1.02 - Changed to call EventAvail so that we don't lose some important
  1320.         events. */
  1321.      
  1322.     for (count = 1; count <= 3; count++)
  1323.         EventAvail(everyEvent, &event);
  1324.     
  1325.     /*    Ignore the error returned from SysEnvirons; even if an error occurred,
  1326.         the SysEnvirons glue will fill in the SysEnvRec. You can save a redundant
  1327.         call to SysEnvirons by calling it after initializing AppleTalk. */
  1328.      
  1329.     SysEnvirons(kSysEnvironsVersion, &gMac);
  1330.     
  1331.     /* Make sure that the machine has at least 128K ROMs. If it doesn't, exit. */
  1332.     
  1333.     if (gMac.machineType < 0) BigBadError(eWrongMachine);
  1334.     
  1335.     /*    1.02 - Move TrapAvailable call to after SysEnvirons so that we can tell
  1336.         in TrapAvailable if a tool trap value is out of range. */
  1337.         
  1338.     gHasWaitNextEvent = TrapAvailable(_WaitNextEvent, ToolTrap);
  1339.  
  1340.     /*    1.01 - We used to make a check for memory at this point by examining ApplLimit,
  1341.         ApplicZone, and StackSpace and comparing that to the minimum size we told
  1342.         MultiFinder we needed. This did not work well because it assumed too much about
  1343.         the relationship between what we asked MultiFinder for and what we would actually
  1344.         get back, as well as how to measure it. Instead, we will use an alternate
  1345.         method comprised of two steps. */
  1346.      
  1347.     /*    It is better to first check the size of the application heap against a value
  1348.         that you have determined is the smallest heap the application can reasonably
  1349.         work in. This number should be derived by examining the size of the heap that
  1350.         is actually provided by MultiFinder when the minimum size requested is used.
  1351.         The derivation of the minimum size requested from MultiFinder is described
  1352.         in Sample.h. The check should be made because the preferred size can end up
  1353.         being set smaller than the minimum size by the user. This extra check acts to
  1354.         insure that your application is starting from a solid memory foundation. */
  1355.      
  1356.     if ((long) GetApplLimit() - (long) ApplicZone() < kMinHeap) BigBadError(eSmallSize);
  1357.     
  1358.     /*    Next, make sure that enough memory is free for your application to run. It
  1359.         is possible for a situation to arise where the heap may have been of required
  1360.         size, but a large scrap was loaded which left too little memory. To check for
  1361.         this, call PurgeSpace and compare the result with a value that you have determined
  1362.         is the minimum amount of free memory your application needs at initialization.
  1363.         This number can be derived several different ways. One way that is fairly
  1364.         straightforward is to run the application in the minimum size configuration
  1365.         as described previously. Call PurgeSpace at initialization and examine the value
  1366.         returned. However, you should make sure that this result is not being modified
  1367.         by the scrap's presence. You can do that by calling ZeroScrap before calling
  1368.         PurgeSpace. Make sure to remove that call before shipping, though. */
  1369.     
  1370.     /* ZeroScrap(); */
  1371.  
  1372.     PurgeSpace(&total, &contig);
  1373.     if (total < kMinSpace)
  1374.         if (UnloadScrap() != noErr)
  1375.             BigBadError(eNoMemory);
  1376.         else {
  1377.             PurgeSpace(&total, &contig);
  1378.             if (total < kMinSpace)
  1379.                 BigBadError(eNoMemory);
  1380.         }
  1381.  
  1382.     /*    The extra benefit to waiting until after the Toolbox Managers have been initialized
  1383.         to check memory is that we can now give the user an alert to tell him/her what
  1384.         happened. Although it is possible that the memory situation could be worsened by
  1385.         displaying an alert, MultiFinder would gracefully exit the application with
  1386.         an informative alert if memory became critical. Here we are acting more
  1387.         in a preventative manner to avoid future disaster from low-memory problems. */
  1388.     
  1389.     menuBar = GetNewMBar(rMenuBar);            /* read menus into menu bar */
  1390.     if ( menuBar == nil )
  1391.                 BigBadError(eNoMemory);
  1392.     SetMenuBar(menuBar);                    /* install menus */
  1393.     DisposHandle(menuBar);
  1394.     AddResMenu(GetMHandle(mApple), 'DRVR');    /* add DA names to Apple menu */
  1395.     DrawMenuBar();
  1396.  
  1397.     gNumDocuments = 0;
  1398.  
  1399.     /* do other initialization here */
  1400.  
  1401.     (void) DoNew();                            /* create a single empty document */
  1402. } /*Initialize*/
  1403.  
  1404.  
  1405. /* Used whenever a, like, fully fatal error happens */
  1406. #pragma segment Initialize
  1407. void BigBadError( short error )
  1408. {
  1409.     AlertUser(error);
  1410.  
  1411.     if (gSpeechChan)                        /* SPEECH MANAGER: get rid of channel */
  1412.         error = DisposeSpeechChannel(gSpeechChan);
  1413.  
  1414.     ExitToShell();
  1415. }
  1416.  
  1417.  
  1418. /* Return a rectangle that is inset from the portRect by the size of
  1419.     the scrollbars and a little extra margin. */
  1420.  
  1421. #pragma segment Main
  1422. void GetTERect( WindowPtr window, Rect *teRect )
  1423. {
  1424.     *teRect = window->portRect;
  1425.     InsetRect(teRect, kTextMargin, kTextMargin);    /* adjust for margin */
  1426.     teRect->bottom = (short) (teRect->bottom - 15);        /* and for the scrollbars */
  1427.     teRect->right = (short) (teRect->right - 15);
  1428. } /*GetTERect*/
  1429.  
  1430.  
  1431. /* Update the TERec's view rect so that it is the greatest multiple of
  1432.     the lineHeight that still fits in the old viewRect. */
  1433.  
  1434. #pragma segment Main
  1435. void AdjustViewRect( TEHandle docTE )
  1436. {
  1437.     TEPtr        te;
  1438.     
  1439.     te = *docTE;
  1440.     te->viewRect.bottom = (short) ((((te->viewRect.bottom - te->viewRect.top) / te->lineHeight)
  1441.                             * te->lineHeight) + te->viewRect.top);
  1442. } /*AdjustViewRect*/
  1443.  
  1444.  
  1445. /* Scroll the TERec around to match up to the potentially updated scrollbar
  1446.     values. This is really useful when the window has been resized such that the
  1447.     scrollbars became inactive but the TERec was already scrolled. */
  1448.  
  1449. #pragma segment Main
  1450. void AdjustTE( WindowPtr window )
  1451. {
  1452.     TEPtr        te;
  1453.     
  1454.     te = *((DocumentPeek)window)->docTE;
  1455.     TEScroll((te->viewRect.left - te->destRect.left) -
  1456.             GetCtlValue(((DocumentPeek)window)->docHScroll),
  1457.             (te->viewRect.top - te->destRect.top) -
  1458.                 (GetCtlValue(((DocumentPeek)window)->docVScroll) *
  1459.                 te->lineHeight),
  1460.             ((DocumentPeek)window)->docTE);
  1461. } /*AdjustTE*/
  1462.  
  1463.  
  1464. /* Calculate the new control maximum value and current value, whether it is the horizontal or
  1465.     vertical scrollbar. The vertical max is calculated by comparing the number of lines to the
  1466. [vertical size of the viewRect. The horizontal max is calculated by comparing the maximum document
  1467.     width to the width of the viewRect. The current values are set by comparing the offset between
  1468.     the view and destination rects. If necessary and we canRedraw, have the control be re-drawn by
  1469.     calling ShowControl. */
  1470.  
  1471. #pragma segment Main
  1472. void AdjustHV( Boolean isVert, ControlHandle control, TEHandle docTE, Boolean canRedraw )
  1473. {
  1474.     short        value, lines, max;
  1475.     short        oldValue, oldMax;
  1476.     TEPtr        te;
  1477.     
  1478.     oldValue = GetCtlValue(control);
  1479.     oldMax = GetCtlMax(control);
  1480.     te = *docTE;                            /* point to TERec for convenience */
  1481.     if ( isVert ) {
  1482.         lines = te->nLines;
  1483.         /* since nLines isn’t right if the last character is a return, check for that case */
  1484.         if ( *(*te->hText + te->teLength - 1) == kCrChar )
  1485.             lines += 1;
  1486.         max = (short) (lines - ((te->viewRect.bottom - te->viewRect.top) /
  1487.                 te->lineHeight));
  1488.     } else
  1489.         max = (short) (kMaxDocWidth - (te->viewRect.right - te->viewRect.left));
  1490.     
  1491.     if ( max < 0 ) max = 0;
  1492.     SetCtlMax(control, max);
  1493.     
  1494.     /* Must deref. after SetCtlMax since, technically, it could draw and therefore move
  1495.         memory. This is why we don’t just do it once at the beginning. */
  1496.     te = *docTE;
  1497.     if ( isVert )
  1498.         value = (short) (te->viewRect.top - te->destRect.top) / te->lineHeight;
  1499.     else
  1500.         value = (short) (te->viewRect.left - te->destRect.left);
  1501.     
  1502.     if ( value < 0 ) value = 0;
  1503.     else if ( value >  max ) value = max;
  1504.     
  1505.     SetCtlValue(control, value);
  1506.     /* now redraw the control if it needs to be and can be */
  1507.     if ( canRedraw || (max != oldMax) || (value != oldValue) )
  1508.         ShowControl(control);
  1509. } /*AdjustHV*/
  1510.  
  1511.  
  1512. /* Simply call the common adjust routine for the vertical and horizontal scrollbars. */
  1513.  
  1514. #pragma segment Main
  1515. void AdjustScrollValues( WindowPtr window, Boolean canRedraw )
  1516. {
  1517.     DocumentPeek doc;
  1518.     
  1519.     doc = (DocumentPeek)window;
  1520.     AdjustHV(true, doc->docVScroll, doc->docTE, canRedraw);
  1521.     AdjustHV(false, doc->docHScroll, doc->docTE, canRedraw);
  1522. } /*AdjustScrollValues*/
  1523.  
  1524.  
  1525. /*    Re-calculate the position and size of the viewRect and the scrollbars.
  1526.     kScrollTweek compensates for off-by-one requirements of the scrollbars
  1527.     to have borders coincide with the growbox. */
  1528.  
  1529. #pragma segment Main
  1530. void AdjustScrollSizes( WindowPtr window )
  1531. {
  1532.     Rect        teRect;
  1533.     DocumentPeek doc;
  1534.     
  1535.     doc = (DocumentPeek) window;
  1536.     GetTERect(window, &teRect);                            /* start with TERect */
  1537.     (*doc->docTE)->viewRect = teRect;
  1538.     AdjustViewRect(doc->docTE);                            /* snap to nearest line */
  1539.     MoveControl(doc->docVScroll, window->portRect.right - kScrollbarAdjust, -1);
  1540.     SizeControl(doc->docVScroll, kScrollbarWidth, (window->portRect.bottom - 
  1541.                 window->portRect.top) - (kScrollbarAdjust - kScrollTweek));
  1542.     MoveControl(doc->docHScroll, -1, window->portRect.bottom - kScrollbarAdjust);
  1543.     SizeControl(doc->docHScroll, (window->portRect.right - 
  1544.                 window->portRect.left) - (kScrollbarAdjust - kScrollTweek),
  1545.                 kScrollbarWidth);
  1546. } /*AdjustScrollSizes*/
  1547.  
  1548.  
  1549. /* Turn off the controls by jamming a zero into their contrlVis fields (HideControl erases them
  1550.     and we don't want that). If the controls are to be resized as well, call the procedure to do that,
  1551.     then call the procedure to adjust the maximum and current values. Finally re-enable the controls
  1552.     by jamming a $FF in their contrlVis fields. */
  1553.  
  1554. #pragma segment Main
  1555. void AdjustScrollbars( WindowPtr window, Boolean needsResize )
  1556. {
  1557.     DocumentPeek doc;
  1558.     
  1559.     doc = (DocumentPeek) window;
  1560.     /* First, turn visibility of scrollbars off so we won’t get unwanted redrawing */
  1561.     (*doc->docVScroll)->contrlVis = kControlInvisible;    /* turn them off */
  1562.     (*doc->docHScroll)->contrlVis = kControlInvisible;
  1563.     if ( needsResize )                                    /* move & size as needed */
  1564.         AdjustScrollSizes(window);
  1565.     AdjustScrollValues(window, needsResize);            /* fool with max and current value */
  1566.     /* Now, restore visibility in case we never had to ShowControl during adjustment */
  1567.     (*doc->docVScroll)->contrlVis = kControlVisible;    /* turn them on */
  1568.     (*doc->docHScroll)->contrlVis = kControlVisible;
  1569. } /* AdjustScrollbars */
  1570.  
  1571.  
  1572. /* Gets called from our assembly language routine, ASMCLIKLOOP, which is in
  1573.     turn called by the TEClick toolbox routine. Saves the windows clip region,
  1574.     sets it to the portRect, adjusts the scrollbar values to match the TE scroll
  1575.     amount, then restores the clip region. */
  1576.  
  1577. #pragma segment Main
  1578. pascal void PASCALCLIKLOOP(void)
  1579. {
  1580.     WindowPtr    window;
  1581.     RgnHandle    region;
  1582.     
  1583.     window = FrontWindow();
  1584.     region = NewRgn();
  1585.     GetClip(region);                    /* save clip */
  1586.     ClipRect(&window->portRect);
  1587.     AdjustScrollValues(window, true);    /* pass true for canRedraw */
  1588.     SetClip(region);                    /* restore clip */
  1589.     DisposeRgn(region);
  1590. } /* Pascal/C ClikLoop */
  1591.  
  1592.  
  1593. /* Gets called from our assembly language routine, ASMCLIKLOOP, which is in
  1594.     turn called by the TEClick toolbox routine. It returns the address of the
  1595.     default clikLoop routine that was put into the TERec by TEAutoView to
  1596.     ASMCLIKLOOP so that it can call it. */
  1597.  
  1598. #pragma segment Main
  1599. pascal ProcPtr GETOLDCLIKLOOP(void)
  1600. {
  1601.     return ((DocumentPeek)FrontWindow())->docClik;
  1602. } /* GetOldClikLoop */
  1603.  
  1604.  
  1605. /*    Check to see if a window belongs to the application. If the window pointer
  1606.     passed was NIL, then it could not be an application window. WindowKinds
  1607.     that are negative belong to the system and windowKinds less than userKind
  1608.     are reserved by Apple except for windowKinds equal to dialogKind, which
  1609.     mean it is a dialog.
  1610.     1.02 - In order to reduce the chance of accidentally treating some window
  1611.     as an AppWindow that shouldn't be, we'll only return true if the windowkind
  1612.     is userKind. If you add different kinds of windows to Sample you'll need
  1613.     to change how this all works. */
  1614.  
  1615. #pragma segment Main
  1616. Boolean IsAppWindow( WindowPtr window )
  1617. {
  1618.     short        windowKind;
  1619.  
  1620.     if ( window == nil )
  1621.         return false;
  1622.     else {    /* application windows have windowKinds = userKind (8) */
  1623.         windowKind = ((WindowPeek) window)->windowKind;
  1624.         return (windowKind == userKind);
  1625.     }
  1626. } /*IsAppWindow*/
  1627.  
  1628.  
  1629. /* Check to see if a window belongs to a desk accessory. */
  1630.  
  1631. #pragma segment Main
  1632. Boolean IsDAWindow( WindowPtr window )
  1633. {
  1634.     if ( window == nil )
  1635.         return false;
  1636.     else    /* DA windows have negative windowKinds */
  1637.         return ((WindowPeek) window)->windowKind < 0;
  1638. } /*IsDAWindow*/
  1639.  
  1640.  
  1641. /*    Check to see if a given trap is implemented. This is only used by the
  1642.     Initialize routine in this program, so we put it in the Initialize segment.
  1643.     The recommended approach to see if a trap is implemented is to see if
  1644.     the address of the trap routine is the same as the address of the
  1645.     Unimplemented trap. */
  1646. /*    1.02 - Needs to be called after call to SysEnvirons so that it can check
  1647.     if a ToolTrap is out of range of a pre-MacII ROM. */
  1648.  
  1649. #pragma segment Initialize
  1650. Boolean TrapAvailable( short tNumber, TrapType tType )
  1651. {
  1652.     if ( ( tType == (unsigned char) ToolTrap ) &&
  1653.         ( gMac.machineType > envMachUnknown ) &&
  1654.         ( gMac.machineType < envMacII ) ) {        /* it's a 512KE, Plus, or SE */
  1655.         tNumber = tNumber & 0x03FF;
  1656.         if ( tNumber > 0x01FF )                    /* which means the tool traps */
  1657.             tNumber = _Unimplemented;            /* only go to 0x01FF */
  1658.     }
  1659.     return NGetTrapAddress(tNumber, tType) != GetTrapAddress(_Unimplemented);
  1660. } /*TrapAvailable*/
  1661.  
  1662.  
  1663. /*    Display an alert that tells the user an error occurred, then exit the program.
  1664.     This routine is used as an ultimate bail-out for serious errors that prohibit
  1665.     the continuation of the application. Errors that do not require the termination
  1666.     of the application should be handled in a different manner. Error checking and
  1667.     reporting has a place even in the simplest application. The error number is used
  1668.     to index an 'STR#' resource so that a relevant message can be displayed. */
  1669.  
  1670. #pragma segment Main
  1671. void AlertUser( short error )
  1672. {
  1673.     short        itemHit;
  1674.     Str255        message;
  1675.  
  1676.     SetCursor(&qd.arrow);
  1677.     /* type Str255 is an array in MPW 3 */
  1678.     GetIndString(message, kErrStrings, error);
  1679.     ParamText(message, "\p", "\p", "\p");
  1680.     itemHit = Alert(rUserAlert, nil);
  1681. } /* AlertUser */
  1682.  
  1683. /* maintains globals for detecting double-clicks, triple-clicks, and beyond */
  1684. /* returns current state of gClickMultiple */
  1685.  
  1686. #pragma segment Main
  1687. long TrackMultipleClicks(long when, Point where)
  1688. {
  1689.     if ((when - gLastClickTickCount) < GetDblTime())
  1690.     {
  1691.         if ((abs(where.h - gLastClickWhere.h) < 5)
  1692.         &&  (abs(where.v - gLastClickWhere.v) < 5))
  1693.             gClickMultiple++;                    /* a repeat click has occurred */
  1694.         else
  1695.         {
  1696.             gClickMultiple = 1;                    /* reset if click is outside slop rectangle */
  1697.             gLastClickWhere = where;            /* latch new coord for subsequent clicks */
  1698.         }
  1699.     }
  1700.     else
  1701.     {
  1702.         gClickMultiple = 1;                        /* reset if interval > DoubleTime */
  1703.         gLastClickWhere = where;
  1704.     }
  1705.         
  1706.     gLastClickTickCount = when;                    /* restart timer for next click */
  1707.  
  1708.     return gClickMultiple;
  1709. }
  1710.  
  1711. /* computes character offset of specified line start */
  1712.  
  1713. #pragma segment Main
  1714. short TELineStartOffset( TEHandle te, short theLine)
  1715. {
  1716.     short charOffset;
  1717.     
  1718.     if (!te)                                /* no TERecord to work with */
  1719.         return (-1);
  1720.     
  1721.     if (theLine < 0)                        /* first char of TERecord */
  1722.         charOffset = 0;
  1723.     else if (theLine >= (*te)->nLines)
  1724.         charOffset = (*te)->teLength;        /* just past last char of TERecord */
  1725.     else
  1726.         charOffset = (*te)->lineStarts[theLine];
  1727.     
  1728.     return charOffset;
  1729. }
  1730.  
  1731. /* compute the line in which a particular character offset falls */
  1732. /* returns (-1) if charOffset < 0 and (*te)->nLines if charOffset */
  1733. /* is beyond end of text */
  1734.  
  1735. #pragma segment Main
  1736. short TECharOffsetToLine(TEHandle te, short charOffset)
  1737. {
  1738.     short        theLine;
  1739.     short        i;
  1740.  
  1741.     if (!te)                                /* no TERecord to work with */
  1742.         return (-1);
  1743.     
  1744.     if (charOffset < 0)
  1745.         theLine = -1;    
  1746.     else if (charOffset >= (*te)->teLength)
  1747.         theLine = (*te)->nLines;
  1748.     else if ((*te)->nLines == 1)            /* only one line */
  1749.         theLine = 0;        
  1750.     else 
  1751.     {
  1752.         theLine = (*te)->nLines;            /* assume we are off the end */
  1753.         
  1754.         for (i = 0; i < (*te)->nLines; i++)
  1755.         {
  1756.             if (charOffset >= (*te)->lineStarts[i] && charOffset < (*te)->lineStarts[i+1])
  1757.             {
  1758.                 theLine = i; /* this is the line we want */
  1759.                 break;
  1760.             }
  1761.         }
  1762.     }
  1763.     
  1764.     return theLine;            
  1765. }
  1766.  
  1767. /* selects the specified line in a TERecord.  If theLine is beyond end of text, */
  1768. /* the insertion point is positioned after the last char.  If theLine is negative, */
  1769. /* the insertion point is placed before the first char. */
  1770.  
  1771. #pragma segment Main
  1772. void TESelectLine(TEHandle te, short theLine)
  1773. {
  1774.     short        sIndex;
  1775.     short        eIndex;
  1776.         
  1777.     if (!te)                                /* nothing to select */
  1778.         return;
  1779.     
  1780.     sIndex = TELineStartOffset(te, theLine);
  1781.     eIndex = TELineStartOffset(te, theLine + 1);
  1782.     
  1783.     TESetSelect(sIndex, eIndex, te);
  1784. }
  1785.  
  1786. /* Speak some text in the text edit record */
  1787.  
  1788.  
  1789.  
  1790.  
  1791. #pragma segment Main
  1792. OSErr SpeakTextRange(TEHandle te, short sIndex, short eIndex)
  1793. {
  1794.     long         i;
  1795.     long        len;
  1796.     Ptr            textPtr;
  1797.     OSErr        err = noErr;
  1798.  
  1799.     if (!te)                        /* no TERecord to work with */
  1800.         return nilHandleErr;
  1801.     
  1802.     textPtr = *((*te)->hText);        /* get ptr to TERecord text */
  1803.     
  1804.     len = eIndex - sIndex;            /* total length of text to speak */
  1805.     
  1806.     if (len <= 0)                    /* nothing to speak */
  1807.         return noErr;
  1808.     
  1809.     if (len > 4095)
  1810.         len = 4095;
  1811.         
  1812.     for (i = 0; i < len; i++)        /* copy over the chars we want to speak */
  1813.         gTextBuf[i] = textPtr[sIndex + i];
  1814.  
  1815.     gTextBufLen = (unsigned short) len;
  1816.     
  1817.     if (len > 255)
  1818.         len = 255;                    /* limit length to Str255 max for now */
  1819.         
  1820.     for (i = 1; i <= len; i++)        /* copy over the chars we want to speak */
  1821.         gSpeechStr[i] = textPtr[sIndex + i - 1];
  1822.         
  1823.     gSpeechStr[0] = (unsigned char) len;
  1824.                             
  1825.     if (!gSpeechChan)
  1826.         {
  1827.         if (voiceSel == 0)
  1828.             err = NewSpeechChannel(0, &gSpeechChan);
  1829.         else
  1830.             err = NewSpeechChannel(&vspec[voiceSel], &gSpeechChan);
  1831.  
  1832.         if (err != noErr)
  1833.             AlertUser(eSpeechManager);        /* some kind of error */
  1834.         }
  1835.  
  1836.     if (err == noErr)
  1837.     {
  1838.             if (!SpeechBusy())
  1839.             {
  1840.                 err = SpeakBuffer(gSpeechChan, (Ptr) gTextBuf, gTextBufLen, 0);
  1841.                 
  1842.                 if (err != noErr)
  1843.                     AlertUser(eSpeechManager);        /* some kind of error */
  1844.             }
  1845.             else
  1846.                 SysBeep(10);
  1847.     }
  1848.  
  1849.     return err;
  1850. }
  1851.  
  1852.  
  1853.  
  1854.  
  1855.  
  1856. #pragma segment Main
  1857. void StartupSpeech( void )
  1858. {
  1859.     OSErr                err;
  1860.     short                voiceCount;
  1861.     short                i;
  1862.     VoiceDescription    vd;
  1863.     MenuHandle            voiceMenu;
  1864.     NumVersion            ver = SpeechManagerVersion();
  1865.  
  1866.     #ifndef forRez
  1867.     enum {development=0x20, alpha=0x40, beta=0x60, final=0x80, release=0x80};
  1868.     #endif
  1869.  
  1870.     #define kMgrMajorVersion         1                /* 8-bits */
  1871.     #define kMgrMinorVersion         0                /* 4-bits */
  1872.     #define kMgrBugFixVersion         0                /* 4-bits */
  1873.     #define kMgrDevelopmentStage     alpha            /* 8-bits */
  1874.     #define kMgrNonRelVersion        2                /* 8-bits */
  1875.     
  1876.     #define kSpeechManagerVersion     ((kMgrMajorVersion        << 24)         \
  1877.                                     | (kMgrMinorVersion     << 20)         \
  1878.                                     | (kMgrBugFixVersion     << 16)         \
  1879.                                     | (kMgrDevelopmentStage << 8)          \
  1880.                                     | (kMgrNonRelVersion))
  1881.                                     
  1882.     voiceMenu = GetMHandle (mVoice);
  1883.  
  1884.     err = CountVoices(&voiceCount);
  1885.     if (voiceCount > kMaxVoices-1) voiceCount = kMaxVoices-1;
  1886.     for (i = 1; i <= voiceCount; i++)
  1887.         {
  1888.         err = GetIndVoice(i, &vspec[i]);
  1889.         
  1890.         if ( true || ((*( unsigned long *) (&ver)) >= kSpeechManagerVersion)) 
  1891.         {    // newer versions expect you to pass length in parameter list
  1892.             err = GetVoiceDescription(&vspec[i], &vd, sizeof(VoiceDescription));
  1893.         }
  1894.         else 
  1895.         {
  1896.             //vd.length = sizeof(VoiceDescription);    // early versions require you to set length field
  1897.             //err = GetVoiceDescription(&vspec[i], &vd);
  1898.         }
  1899.         AppendMenu (voiceMenu, vd.name);
  1900.         }
  1901.     voiceSel = 0;                        // use Default voice
  1902. }
  1903.  
  1904.